package trunk.component;

import trunk.control.Control;
import trunk.control.Launcher;


import java.util.ArrayList;
import java.util.TimerTask;

/**
 * Created by IntelliJ IDEA.
 * User: yipeipei
 * Date: 12/25/11
 * Time: 1:51 AM
 * To change this template use File | Settings | File Templates.
 */
public class StatusAlterTask extends TimerTask {
    Control control = Control.getInstant();
    ArrayList<StatusAlterable> componentList;
    private int FLAG = 0;

    public StatusAlterTask(ArrayList<StatusAlterable> componentList) {
        this.componentList = componentList;
    }

    public StatusAlterTask(ArrayList<StatusAlterable> componentList, int flag) {
        this.componentList = componentList;
        this.FLAG = flag;
    }

    @Override
    public void run() {
        if (this.FLAG == 0) {

            for (StatusAlterable comp : componentList) {
                comp.setStatus(Status.ACTIVE);
                Launcher.simulator.repaint();
                try {
                    Thread.sleep(control.getSpeed() * 100); //TODO time to sleep
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //after a microcode executed, sleep a longer time
//        try {
//            Thread.sleep(control.getSpeed() * 200);
//        } catch (InterruptedException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//        }
            waitUntilContinue();
            //single step wait
            singleStepWait();
        } else if (this.FLAG == 1) {

            //change components to normal
            for (StatusAlterable comp : componentList) {
                comp.setStatus(Status.NORMAL);
                Launcher.simulator.repaint();
            }
        }
    }

    private boolean waitUntilContinue() {
        if (control.isPauseFlag()) {
            while (control.isPauseFlag()) {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            ;
        }

        return true;
    }

    private boolean singleStepWait() {
        if (control.isStepFlag()) {
            while (control.isStepFlag()) {
                Launcher.simulator.getParameterPanel().btnPause_Pause();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }

            control.setStepFlag(true);
        }


        return true;
    }
}
